package com.googlecode.lookie.imagedb.internal;

import java.io.File;
import java.io.IOException;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.core.Ordered;
import org.springframework.jdbc.datasource.SimpleDriverDataSource;
import org.springframework.richclient.settings.xml.XmlSettingsFactory;

import com.googlecode.lookie.platform.state.StateLocation;

public class StateLocationPostProcessor
    implements BeanPostProcessor, Ordered
{

    private StateLocation stateLocation;

    public void setStateLocation( StateLocation stateLocation )
    {
        this.stateLocation = stateLocation;
    }

    public Object postProcessAfterInitialization( Object bean, String beanName )
        throws BeansException
    {

        if ( beanName.equals( "imageDataSource" ) && bean != null )
        {
            SimpleDriverDataSource dataSource = (SimpleDriverDataSource) bean;
            File file = null;
            try
            {
                file = new File( stateLocation.getDirectory( "lookie.app.imagedb" ), "imagedb" );
            }
            catch ( IOException e )
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            String url = String.format( "jdbc:hsqldb:file:%s;create=true", file.getAbsolutePath() );
            dataSource.setUrl( url );
        }

        if ( bean instanceof XmlSettingsFactory )
        {
            XmlSettingsFactory factory = (XmlSettingsFactory) bean;
            File file = null;
            try
            {
                file = stateLocation.getDirectory( "lookie.app.state" );
            }
            catch ( IOException e )
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            factory.setLocation( file.getAbsolutePath() );
        }

        return bean;
    }

    public Object postProcessBeforeInitialization( Object bean, String beanName )
        throws BeansException
    {
        return bean;
    }

    public int getOrder()
    {
        return Integer.MAX_VALUE;
    }

}
